import Addition2 from '@/components/Addition2';
import {s_saveMaterialUserDefine, s_getMaterialCategoryTree, s_getMaterialDocument, s_getMaterialUserDefine, s_getOrgTargetKeysGlobal, s_getOrgTransferData, s_saveAllocateOrgGlobal, s_saveMaterialInfo, s_saveUnitData, getCommTreeByXid, status2text, s_getTableInfo, s_updateInfo, s_operateInfo, s_getDocument, s_getSelectTree, s_getSelectData } from '@/services/basis';
import { getSelection } from '@/services/selections';
import { ActionType, EditableFormInstance, EditableProTable, ProCard, ProColumns, ProForm, ProFormDatePicker, ProFormDigit, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea, ProFormTreeSelect, ProTable } from '@ant-design/pro-components';
import { useModel, useRequest } from '@umijs/max';
import { Card, theme,Row,Col,Tree, Space, Button, Form, Input, Modal, Radio, Select, DatePicker, Drawer, Transfer, Divider, Checkbox, Tabs, TabsProps, message, Tag} from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { Image } from 'antd';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
 
//分类组件
 function CategoryTree(props:any){
  return(
    <Tree treeData={props.tdata}  
     defaultExpandAll={true} blockNode={true}
          onClick={(e,node)=>{props.getTreeInfo(node);}}/>
  );
}

  
const Welcome: React.FC = () => {
  //选中的物料分类码。因需用于新增表单中，故{}
  const [selectedCategory,setSelectedCategory]=useState(0);       //选择的分类ID
  const [selectedCateNode,setSelectedNode]=useState<{title:string}>();            //选择的树节点
  const [treeData,setTreeData]=useState();                        //分类树数据源
  const [tdata,setTdata]=useState();                               //档案表格数据源
  const [selectedRecords,setSelectedRecords]=useState<DataType[]>([]);           //选中的编码,
  const [selectedRecords2,setSelectedRecords2]=useState<DataType2[]>([]);//工作组参数表

  const [openInfo,setOpenInfo]=useState(false);//显示BOM窗口
  const [etype,setEtype]=useState(0);   //1新增 0修改

  const [openParam,setOpenParam]=useState(false);//显示工作组参数表窗口
  const [open2,setOpen2]=useState(false);//新增或编辑参数
  const [etype2,setEtype2]=useState(0);//参数新增或编辑
  const [dataType,setDataType]=useState({type:1,range:null,range2:[{value:'',label:''}]});//用于动态生成参数的默认值组件。1文本，2数值，3下拉框
   
  const [selectedKeys,setSelectedKeys]=useState<any[]>([]);//树选择的本级节点及下节点
  

   const formRef=useRef<ProFormInstance>();//编辑表单
   const table_ref=useRef<ActionType>();//用于向物料档案组件表传递引用

   const formRef2=useRef<ProFormInstance>();//工作组参数引用
   const table_ref2=useRef<ActionType>();
   const [expandKeys,setExpandKeys]=useState([]);

   const { initialState, setInitialState } = useModel('@@initialState');
   const [selectedLineKeys,setSelectedLineKeys]=useState<any[]>([]);
      
   interface DataType{
    // id,x_id,code,name,workcenter_id,isdefault,status,
    // operater_id,operate_time,type,
    // workcenter_name,operater_name
   id?:number,x_id?:number,code?:string,name?:string,cate_id?:number,isdefault?:number,status?:number,
    operater_id?:number,operate_time?:string,type?:number,
    workcenter_name?:string,operater_name?:string
  }

  const columns:ProColumns<DataType>[]=[
    {dataIndex:'id',title:'id',hidden:true,}, {dataIndex:'x_id',title:'x_id',hidden:true,},
    {dataIndex:'workcenter_name',title:'所属工作中心'},
    {dataIndex:'code',title:'工作组编码'}, {dataIndex:'name',title:'工作组名称'},
    {dataIndex:'isdefault',title:'默认组',valueType:'radio',
       valueEnum:{1:{text:'是'},0:{text:'否',status:'error'}}
    }, 
    {dataIndex:'type',title:'类型',valueType:'select',
        valueEnum:{1:{text:'生产线'},2:{text:'设备'},3:{text:'小组'},4:{text:'个人'}},
    },
    {dataIndex:'operater_name',title:'操作人'}, 
    {dataIndex:'operate_time',title:'操作时间',valueType:'date'},
    {dataIndex:'status',title:'状态',
      render:(text:any)=>status2text(text),
    }, 
  ];

  //工作组参数表
  interface DataType2{
    //  id,workgroup_id,code,name,default_value,status,operater_id,operater_name,operate_time,
    id?:number,workgroup_id?:number,code?:string,name?:string,default_value?:string,data_default?:string,
    status?:number,operater_id?:number,operater_name?:string,operate_time?:string,usetype?:number,
  };

  //工作组列
  const columns2:ProColumns<DataType2>[]=[
    {dataIndex:'id',title:'ID'},{dataIndex:'workgroup_id',title:'工作组ID'},
    {dataIndex:'code',title:'参数编码'},{dataIndex:'name',title:'参数名称'},
    {dataIndex:'usetype',title:'参数类型',valueType:'select',
      valueEnum:{1:{text:'技术'},2:{text:'设备'},3:{text:'工装模具'},4:{text:'材料'},5:{text:'人'}}
    },
    {dataIndex:'default_value',title:'默认值'},
    {dataIndex:'operate_time',title:'日期',valueType:'date'},
    {dataIndex:'status',title:'状态',
      valueEnum:{1:{text:'正常'},2:{text:'关闭'},3:{text:'删除',status:'error'}}
    },
  ];

 //此处创建一个生成树的通用方法，通过传入表名和X_ID值
 useRequest(()=>getCommTreeByXid({x_id:1,source_table:'workcenter'}),{  
  onSuccess:(data)=>{
    setTreeData(data.ctree);
    setExpandKeys(data.keys);
  },
});

  //获取档案
//  useRequest(()=>s_getDocument({x_id:1,cate_id:[],id:0,source:'v_workgroup'}),{
//          onSuccess:(data:any)=>{
//           //  alert(JSON.stringify(data));
//             setTdata(data[0]);
//          },
//      }
//   );
  
  //根据左侧选择的类别，右侧表格显示明细--注意：此处传入的是树节点node(key,title) 
  //---先取本节点及下级节点值，再共同选---------------------------------------------开始-----------------
  var arr:any[]=[];
   //定义一个递归函数，获取选中节点下的所有key
   function getNodeKeys(node:{key:any,title:any,children:any[]}){
        if(node.children.length>0)
              node.children.map((item:any)=>{
                 arr.push(item.key);
                 if(item.children.length>0){
                      arr.push(getNodeKeys(item));
                 }
             });
      }

  async function getDocumentList(node:any){
     // alert( (curCategory));
      setSelectedRecords([]);
      setSelectedCategory(node.key);
      setSelectedNode(node);
     
     arr=[];//先置为空，再取数据
     arr.push(node.key);
     getNodeKeys(node);
     setSelectedKeys(arr.filter((item)=>item!=null));//当前选中的组织的所有下级ID

    //  alert(JSON.stringify(arr));
    //  const x=await s_getDocument({x_id:1,cate_id:arr,id:0,source:'v_workgroup'});
     //alert(JSON.stringify(x.data[0]));
    //  setTdata(x.data[0]);
    table_ref.current?.reloadAndRest?.();
  }
 //---先取本节点及下级节点值，再共同选---------------------------------------------结束-----------------

  //编辑档案信息
  async function editDocumentInfo(){
     if(selectedRecords.length===0)
         message.warning('请先选择要修改的档案项');
     if(selectedRecords[0].status==2||selectedRecords[0].status==2)
        message.warning('不能编辑已关闭、已删除的数据。请选恢复再操作。');
      else{
        setEtype(0);
        setSelectedKeys([selectedRecords[0].cate_id]);
        setOpenInfo(true);
      };
  }

  //新增档案信息
    async function addDocumentInfo(){
         if(selectedCategory===0)
            message.warning('请先选择工作中心');
         else{
            setEtype(1);
            setOpenInfo(true);  
         }
    }

  //保存档案信息
   async function saveDocumentInfo(){
          //获取表单数据
          var fdata=formRef.current?.getFieldsValue();
          if(selectedCategory!=0)
                fdata={...fdata,cate_id:selectedCategory};
          const y=await s_updateInfo({x_id:1,source:'workgroup',operater_id:initialState?.currentUser?.userid,etype,fdata});
            // alert('dddd');
            //  alert(JSON.stringify(fdata));
            if(y.success){
                    message.success('保存成功');
                    table_ref.current?.reloadAndRest?.();
              }else
                    message.error('保存失败，请联系管理员');
      }

      //  审核与取消审核2025-03-15
            async function operateInfo(n:number){
             // source,x_id,operater_id,otype,id
             var id=selectedRecords.length>0?selectedRecords[0].id:0;
             if(selectedRecords.length==0)
                message.warning('请选择要操作的行');
             else{
              const x=await s_operateInfo({x_id:1,source:'workgroup',operater_id:initialState?.currentUser?.userid,otype:n,id});
              if(x.success){
                message.success('操作成功');
                  table_ref.current?.reloadAndRest?.();
              }else
                message.error('操作错误，请联系管理员。');
             }
          }
 
  //显示工作组参数表
 function editParam(){
    if(selectedRecords.length==0)
      message.warning('请先选择工作组');
    else
      setOpenParam(true);
 }         

 //新增工作组参数
 function addParam(){
    setEtype2(1);
    setOpen2(true);
 };
  //编辑工作组参数
  function editParam2(){
    if(selectedRecords2.length==0)
      message.warning('请先选择工作组');
    else{
      setEtype2(0);
      setOpen2(true);
    }
 } 

 //保存工作组参数
async function saveParam(){
   const fdata=formRef2.current?.getFieldsValue();
  //  alert(JSON.stringify({...fdata,workgroup_id:selectedRecords.length>0?selectedRecords[0].id:0}));
   const x=await s_updateInfo({source:'workgroup_param',x_id:1,operater_id:initialState?.currentUser?.userid,etype:etype2,
    fdata:{...fdata,workgroup_id:selectedRecords.length>0?selectedRecords[0].id:0}});
   if(x.success){
       message.success('保存成功');
       table_ref2.current?.reloadAndRest?.();
   }
   else
    message.error('保存失败，请联系管理员');

}


// 操作工作组参数
async function operate(otype:number){
        const id=selectedRecords2[0].id;
        //s_operateInfo({source:'base_ware',operater_id:1,type:tabKey,otype,id})通用表格操作冻结删除
        const x=await s_operateInfo({source:'workgroup_param',x_id:1,operater_id:initialState?.currentUser?.userid,otype,id});

        if(x.success){
            message.success('更新成功。');
            table_ref2.current?.reloadAndRest?.();
        }else
           message.error('更新失败，请联系管理员。');
    }

//   主窗体=================================================================================
  return<>
     <Row gutter={10}>
     <Col  span={6}>
     <ProCard title='工作中心' style={{height:'75vh'}}>
         {/* <CategoryTree tdata={treeData} getTreeInfo={getDocumentList}/> */}
         <Tree treeData={treeData}   blockNode={true}
               expandedKeys={expandKeys}
               onExpand={(keys:any)=>setExpandKeys(keys)}
               onClick={(e,node)=>getDocumentList(node)}
            />
     </ProCard>
     </Col>
     <Col  span={18}>
      <ProCard title='工作组档案'  style={{height:'75vh',overflow:'auto'}} id='drawer_id'
       
      extra={<Space size='large'>
      <Button  onClick={()=>addDocumentInfo()}>新增工作组</Button>
      <Button  onClick={()=>editDocumentInfo()}>编辑工作组</Button>
      {/* <Button  onClick={()=>editParam()}>工作组参数</Button> */}
      <Button  onClick={()=>operateInfo(2)}>关闭</Button> 
      <Button  onClick={()=>operateInfo(3)}>删除</Button> 
      <Button  onClick={()=>operateInfo(1)}>恢复</Button> 
      </Space>}
      >
           <ProTable 
                // dataSource={tdata}
                columns={columns} 
                rowKey='id' 
                rowSelection={{
                     type:'radio',
                     selectedRowKeys:selectedLineKeys,
                     onChange:(selectedKeys,selectedRows)=>{
                            setSelectedRecords(selectedRows);
                            setSelectedLineKeys(selectedKeys);
                          },
                }}
                 onRow={(record)=>{
            return {
              onClick:()=>{
                const k=record.id;
                // if(selectedKeys.includes(k) )
                //      setSelectedKeys(selectedKeys.filter(item=>item.id!=k));
                // else
                     setSelectedLineKeys([k]);
                     setSelectedRecords([record]);
              },
            }
           }}
                scroll={{y:500}}
                options={false}
                actionRef={table_ref}
                pagination={{
                    size:'small',
                    pageSize:10,
                  }}
                search={false}
                request={async ()=>{
                    const x=await s_getDocument({x_id:1,cate_id:selectedKeys,id:0,source:'v_workgroup'});
                    // alert(JSON.stringify(x.data[0]));
                    return {
                        data:x.data[0],
                        success:true,
                    }
                }}
               />
      </ProCard>
      </Col>
     </Row>

    
     <Modal open={openInfo}  width='50%'   maskClosable={false}  okButtonProps={{hidden:true}}
         destroyOnClose={true} closable={true} onCancel={()=>setOpenInfo(false)} cancelButtonProps={{hidden:true}}
     >  
       <ProCard title={etype==1?'新增工作组档案':'编辑工作组档案'} 
          style={{height:600,overflow:'auto'}} 
          extra={<Space size='large'>
            <Button onClick={()=>formRef.current?.submit()} >保存</Button>
            <Button onClick={()=>setOpenInfo(false)}>退出</Button>
          </Space>}  >
       
          <ProForm formRef={formRef} submitter={false} labelAlign='left' layout='horizontal' 
               labelCol={{offset:0,span:8}}
               initialValues={etype==0&&selectedRecords.length>0?{
                                  ...selectedRecords[0],
                              }:{
                                  isdefault:0,
                                  status:1,
                                  operate_time:moment().format('YYYY-MM-DD'),
                                  type:1,
                                  operater_id:initialState?.currentUser?.userid,
                           }}
                onFinish={()=>saveDocumentInfo()}
          >
  
            <ProFormText name='id' hidden={true}/><ProFormText name='cate_id' hidden={true} /> 
            <ProFormText name='code' label='工作组编码' width={200}/>
            <ProFormText name='name' label='工作组名称' width={200}/>

            <ProFormTreeSelect name='cate_id' label='所属工作中心' width={200}
                 request={async ()=>{
                    const x=await s_getSelectTree({x_id:1,source:'workcenter'});
                    // alert(JSON.stringify(x.data));
                    // setCategoryOption(x.data);
                    return x.data;
                  }}
                fieldProps={{
                  showSearch:true,
                //   onSelect(value, option) {
                //     // alert(JSON.stringify(option));
                //     getCategoryIds(option);
                //   },
                  treeNodeFilterProp:'title',
                  treeDefaultExpandAll:true,
                }}  
                />
            <ProFormRadio.Group name='isdefault' label='是否默认' width={200}
               options={[{value:0,label:'否'},{value:1,label:'是'}]}
                />
            <ProFormRadio.Group name='type' label='工作组类型' width={200}
               options={[{value:1,label:'生产线'},{value:2,label:'设备'},{value:3,label:'小组'},{value:4,label:'个人'}]}
              />
            <ProFormDatePicker name='operate_time' label='操作时间' width={200}/>
            <ProFormRadio.Group name='status' label='状态' width={200}
                     rules={[{required:true,message:'此为必填项'}]}
                     options={[{value:0,label:'未审核'},{value:1,label:'正常'},{value:2,label:'关闭'},
                          {value:5,label:'已审核'},{value:6,label:'弃审'},
                          {value:3,label:'删除'}]}
                 />
             <ProFormSelect name='operater_id' label='操作人' width={200}
                   fieldProps={{
                     showSearch:true,
                    }}
                    request={async ()=>{
                      var x:any=await getSelection({source: 'base_person', x_id: 1 });
                      var x2=x.data.map((item:any)=>({value:item.id,label:item.name}));
                      return x2;
                    }}    
                 />
        </ProForm>
       </ProCard>  
     </Modal>

     {/* 工作组参数表----------------------------------- */}
     <Modal  open={openParam} destroyOnClose cancelButtonProps={{hidden:true}} width='60%'
        okButtonProps={{hidden:true}} onCancel={()=>setOpenParam(false)} onClose={()=>setOpenParam(false)}
     >
         <ProCard title='工作组参数表' style={{height:600,overflow:'auto'}}
           extra={<Space>
             <Button onClick={()=>addParam()}>新增参数</Button>
             <Button onClick={()=>editParam2()}>编辑参数</Button>
             <Button onClick={()=>operate(2)}>关闭</Button>
             <Button onClick={()=>operate(3)}>删除</Button>
             <Button onClick={()=>operate(1)}>恢复</Button>
           </Space>}
         >
             {/* {JSON.stringify(selectedRecords)} */}
            <ProTable<DataType2>
                actionRef={table_ref2}
               search={false}
               options={false}
               columns={columns2}
               rowKey='id'
               rowSelection={{
                type:'radio',
                onChange(selectedRowKeys, selectedRows, info) {
                  setSelectedRecords2(selectedRows);
                },
               }}
               request={async ()=>{
                const x=await s_getTableInfo({x_id:1,source:'v_workgroup_param',
                                       id:selectedRecords.length==0?0:selectedRecords[0].id});
                //  alert(JSON.stringify(x.data));                      
                return {
                  data:x.data,
                  success:true,
                }
               }}
              />
         </ProCard>
     </Modal>

    {/* 工艺参数新增/编辑窗口 */}
     <Modal  open={open2} destroyOnClose onCancel={()=>setOpen2(false)} onClose={()=>setOpen2(false)}
        okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}} width='50%' >
         <ProCard title={etype2==1?'新增参数':'编辑参数'}
             extra={<Space>
              <Button onClick={()=>formRef2.current?.submit()}>保存参数</Button>
              <Button onClick={()=>setOpen2(false)}>退出</Button>
             </Space>}
          >
            <ProForm formRef={formRef2} layout='horizontal' labelAlign='left' labelCol={{offset:0,span:5}}
               submitter={false}
               onFinish={()=>saveParam()}
               initialValues={etype2==0&&selectedRecords2.length>0?{
                    ...selectedRecords2[0],data_default:selectedRecords2[0].default_value,
                  }:{
                     status:1
                  }}
               >
            <ProFormText name='id' hidden={true}/>
             <ProFormSelect name='craft_param_id' label='工艺参数' width={200}
                rules={[{required:true,message:'必填项'}]}
                showSearch 
                request={async ()=>{
                const x=await s_getSelectData({x_id:1,source:'craft_param'});
                      return x.data;
                    }}
                fieldProps={{
                  async onChange(value, option) {
                    //在此处，value为ID值，即工艺的ID，需要根据此带出默认值
                    // alert(value);
                    const x=await s_getTableInfo({x_id:1,source:'craft_param',id:value});
                     alert(JSON.stringify(x.data[0].data_range));
                      var y=x.data[0].data_range!=undefined?JSON.parse(x.data[0].data_range):[];
                      var opt=[{value:'',label:''}];
                    if(x.data[0].data_type==3&&y.length>0){
                          opt=y.map((item:any)=>{
                              return {value:item,label:item};
                        });
                      };
                      
                    setDataType({type:x.data[0].data_type,
                                 range:x.data[0].data_range,
                                 range2:opt}
                                 );
                    formRef2.current?.setFieldsValue({
                      usetype:x.data[0].usetype,
                      data_range:x.data[0].data_range,
                      data_default:x.data[0].data_default,
                     });
                    

                  },
                }}
                />
                <ProFormRadio.Group name='usetype' label='类型' 
                 rules={[{required:true,message:'必填项'}]}
                   options={[{value:1,label:'技术'},{value:2,label:'设备'},{value:3,label:'工装模具'},
                              {value:4,label:'材料'},{value:5,label:'人'}]}
                  />
      
                <ProFormTextArea name='data_range' label='取值范围' width={200} />
                {dataType.type==1?<ProFormText name='data_default' label='默认值' width={200} />
                                  :dataType.type==2?<ProFormDigit name='data_default' label='默认值' width={200} />
                                  :<ProFormSelect name='data_default' label='默认值' width={200} showSearch
                                     options={dataType.range2}
                                  />
                 }
                <ProFormRadio.Group name='status' label='状态' 
                  options={[{value:1,label:'正常'},{value:2,label:'关闭'},{value:3,label:'删除'}]} />
                </ProForm>
       </ProCard>
        </Modal>
  </>
};

export default Welcome;


